package logic

import (
	"bufio"
	"net/http"
	"os"
	"tiktok/dao"
	"tiktok/models"
	"tiktok/web"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

var (
	playstr string = "\\"
	covstr  string = "\\"
)

type insertdb struct {
	models.Video
	Uid      int64 `gorm:"author"`
	Sub_time int64 `gorm:"sub_time"`
}

func SubVider(ctx *gin.Context) {
	token := ctx.PostForm("token")
	title := ctx.PostForm("title")
	data := ctx.PostForm("data")
	db := dao.GetDB(ctx)

	userCalim, err := web.ParseToken(token)
	if err != nil { //解析token失败
		logrus.Error("logic,web.ParseToken:解析token失败...")
		ctx.JSON(http.StatusBadRequest,
			models.Status{
				StatusCode: -1,
				StatusMsg:  "服务器内部错误！",
			})
		return
	}

	//文件操作
	filename := playstr + title + ".mp4"
	file, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		logrus.Error("logic,os.opefile:打开文件失败...")
		ctx.JSON(http.StatusBadRequest,
			models.Status{
				StatusCode: -1,
				StatusMsg:  "服务器内部错误！",
			})
		return
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	//写入文件
	_, err = writer.Write([]byte(data))
	if err != nil {
		logrus.Error("logic,os.write:写文件失败...")
		ctx.JSON(http.StatusBadRequest,
			models.Status{
				StatusCode: -1,
				StatusMsg:  "服务器内部错误！",
			})
		return
	}
	writer.Flush()

	err = db.Table("tiktok_video").Create(
		insertdb{
			Uid: userCalim.Uid,
			Video: models.Video{
				PlayUrl:       playstr,
				CoverUrl:      covstr,
				FavoriteCount: 0,
				CommentCount:  0,
				Title:         title,
			},
			Sub_time: time.Now().Unix(),
		}).Error
	if err != nil {
		logrus.Error("logic,db.creat:插入数据失败...")
		ctx.JSON(http.StatusBadRequest,
			models.Status{
				StatusCode: -1,
				StatusMsg:  "服务器内部错误！",
			})
		return
	}
	ctx.JSON(http.StatusOK, models.Status{StatusCode: 0, StatusMsg: "投稿成功！"})
}
